import {
    Avatar, Button,
    Dropdown,
    DropdownItem,
    DropdownMenu,
    DropdownTrigger,
    Input,
    Modal, ModalBody, ModalContent, ModalFooter, ModalHeader,
    NavbarContent, Spacer, Switch, Textarea, Tooltip, useDisclosure
} from "@nextui-org/react";
import { MailIcon, MoonIcon, SearchIcon, SunIcon } from "@nextui-org/shared-icons";
import React, { useEffect, useLayoutEffect, useState } from "react";
import { FiUser } from "react-icons/fi";
import { MdMoreTime } from "react-icons/md";
import UserInfoService from "@/app/service/userInfoService";
import cookie from "react-cookies";
import { Token, UserName } from "@/app/constants/authTokenConstants";
import { decodeFromBase64 } from "next/dist/build/webpack/loaders/utils";
import Profile from "@/app/pages/profile/Profile";
import { KeyboardEvent } from "@react-types/shared/src/events";
import PubSub from "pubsub-js";
import { BiCertification, BiHotel, BiLogOutCircle, BiMehBlank } from "react-icons/bi";
import { useTheme } from "next-themes";
import { className } from "postcss-selector-parser";
import { Divider } from "@nextui-org/divider";
import ToastUtil from "@/app/utils/toastUtil";
import SettingPage from "@/app/components/profile/SettingPage";
import { SiNamebase } from "react-icons/si";
import { AiFillCamera } from "react-icons/ai";
import { CiFries } from "react-icons/ci";
import ModifyInfo from "@/app/service/ModifyInfo";
import uploadAvatarService from "@/app/service/uploadAvatarService";
import SearchModal from "@/app/components/search/SearchModal";

/**
 * 个人中心头像点击时的组件和状态
 * @param username
 * @param isExit
 * @param setExit
 * @param setInSearch
 * @constructor
 */
export default function OnAuthenticatedNavbarContent({
    username,
    isExit,
    setExit,
    setInSearch
}: any) {
    const { isOpen, onOpen, onOpenChange } = useDisclosure();

    /*邮箱和创建时间状态*/
    const [nickname, setNickname] = useState('')
    const [avatar, setAvatar] = useState('');
    const [email, setEmail] = useState('');
    const [createTime, setCreateTime] = useState('');
    const [mobile, setMobile] = useState('');
    const [newAvatar, setNewAvatar] = useState<File | null>(null);
    const [avatarUrl, setAvatarUrl] = useState(''); // 存储上传后的头像URL
    const [isUploading, setIsUploading] = useState(false); // 上传状态
    const [isEditingEmail, setIsEditingEmail] = useState(false);
    const [newEmail, setNewEmail] = useState('');
    const [isChangingPassword, setIsChangingPassword] = useState(false);
    const [oldPassword, setOldPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [isEditingUsername, setIsEditingUsername] = useState(false);
    const [newUsername, setNewUsername] = useState('');

    /**
     * 加载数据
     */
    const [refresh, setRefresh] = useState(false);
    useLayoutEffect(() => {
        UserInfoService({ setEmail, setCreateTime, setNickname, setAvatar, setMobile }).then();
    }, [refresh])


    /**
     * 头像变化监听
     */
    const handleAvatarChange = async (event: any) => {
        const file = event.target.files[0];
        if (file) {
            setNewAvatar(file);
            // 设置本地预览
            setAvatar(URL.createObjectURL(file));

            // 立即上传头像
            setIsUploading(true);
            try {
                const result = await uploadAvatarService(file);
                if (result.success) {
                    setAvatarUrl(result.url);
                    ToastUtil("头像上传成功", '👌', "success");
                    // 可以选择是否立即更新用户信息
                    // await ModifyInfo(nickname, undefined, undefined, undefined, undefined, result.url);
                    // setRefresh(!refresh);
                } else {
                    ToastUtil("头像上传失败，请重试", '❌', "error");
                }
            } catch (error) {
                ToastUtil("头像上传失败，请重试", '❌', "error");
            } finally {
                setIsUploading(false);
            }
        }
    }

    /**
     * 选择图片
     */
    const handleChoosePhoto = () => {
        const inputElement = document.createElement('input');
        inputElement.type = 'file';
        inputElement.accept = 'image/*';

        inputElement.onchange = (event) => {
            handleAvatarChange(event)
        };

        inputElement.click();
    };

    /**
     * 修改用户名
     */
    const handleChangeUsername = () => {
        if (newUsername && newUsername !== decodeFromBase64(cookie.load(UserName))) {
            // 这里应该有修改用户名的API调用
            // 暂时只是显示提示
            ToastUtil("用户名修改需要登出重新登录才能生效", '⚠️', "warning");
        }
        setIsEditingUsername(false);
    };

    /**
     * 更新信息
     */
    function modifyUserInfo() {
        // 检查新密码和确认密码是否一致
        if (isChangingPassword && newPassword !== confirmPassword) {
            ToastUtil("两次输入的密码不一致", '❌', "error");
            return;
        }

        ModifyInfo(
            nickname,
            undefined, // 不再通过ModifyInfo上传头像文件
            isEditingEmail ? newEmail : undefined,
            isChangingPassword ? oldPassword : undefined,
            isChangingPassword ? newPassword : undefined,
            avatarUrl // 传递已上传的头像URL
        ).then(res => {
            if (res) {
                // 重置状态
                setNewAvatar(null);
                setAvatarUrl('');
                setIsEditingEmail(false);
                setNewEmail('');
                setIsChangingPassword(false);
                setOldPassword('');
                setNewPassword('');
                setConfirmPassword('');
                // 刷新用户信息
                setRefresh(!refresh);
            }
        });
    }

    /**打开i设置*/
    const [isOpenSet, onOpenSetChange] = useState(false);
    /**搜索数据*/
    const [inputValue, setInputValue] = useState('');

    // 搜索模态框状态
    const [isSearchModalOpen, setIsSearchModalOpen] = useState(false);

    const handleKeyDown = (e: KeyboardEvent) => {
        // noinspection JSDeprecatedSymbols
        if (e.keyCode === 13) {
            PubSub.publish('keyword', inputValue);
            setInSearch(true);
        }
    };

    /**
     * 主题切换
     */
    const { theme, setTheme } = useTheme()
    return (
        <>
            <NavbarContent as="div" className="items-center" justify="end">
                <Input
                    classNames={{
                        base: "lg:flex max-w-full sm:max-w-[7rem] h-8",
                        mainWrapper: "h-full",
                        input: "text-small",
                        inputWrapper: "h-full font-normal text-default-500 bg-default-400/20 dark:bg-default-500/20",
                    }}
                    placeholder="搜索文档..."
                    size="sm"
                    startContent={<SearchIcon fontSize={18} />}
                    type="text"
                    variant={'bordered'}
                    onValueChange={(value) => {
                        setInputValue(value)
                    }}
                    onKeyDown={handleKeyDown}
                    onFocus={() => setIsSearchModalOpen(true)}
                />
                <Dropdown placement="bottom-end"
                    className={`dark:text-white light:text-black `}
                    backdrop={"transparent"}
                    size={"sm"}>
                    <DropdownTrigger>
                        <Avatar
                            isBordered
                            as="button"
                            radius="full"
                            className={`transition-transform min-w-8 min-h-8 aspect-square ${isUploading ? 'opacity-50' : ''}`}
                            color="primary"
                            name={username}
                            size="sm"
                            src={avatar == '' ? "https://baiyunshan.flowus.cn/public%2Fe8be5d93-efd7-4efe-9da8-f41d86956b83%2F42428313-3e08-4d25-957c-64e18b5bb15f.jpg?img_process=/resize,w_1000/quality,q_100/" : avatar}
                        />
                    </DropdownTrigger>
                    <DropdownMenu aria-label="Profile Actions" variant="flat">
                        <DropdownItem aria-label={'profile-label'} key="profile" className="h-14 gap-2">
                            <p className="font-semibold">&nbsp;Hi,{nickname}</p>
                            <p className="font-semibold">📝 | 🤪 | 🧑‍💻</p>
                        </DropdownItem>
                        <DropdownItem aria-label={'divider-label'}>
                            <Divider orientation={'horizontal'} />
                        </DropdownItem>
                        <DropdownItem aria-label={'personal_center-label'} key="personal_center" color={"default"}
                            startContent={<BiMehBlank size={18} />}
                            onClick={onOpen}>个人中心</DropdownItem>
                        <DropdownItem aria-label={'settings-label'} key="settings" color={"default"}
                            startContent={<BiCertification size={18} />}
                            onClick={() => onOpenSetChange(!isOpenSet)}>设置中心</DropdownItem>
                        <DropdownItem aria-label={'theme_switch-label'} key='theme_switch'
                            startContent={<BiHotel size={18} />}
                            endContent={
                                <Switch
                                    size="sm"
                                    color="secondary"
                                    isSelected={theme == 'light'}
                                    onValueChange={() => {
                                        theme == 'light' ? setTheme('dark') : setTheme('light')
                                    }}
                                    thumbIcon={({ isSelected, className }) =>
                                        theme == 'light' ? (
                                            <SunIcon className={className} />
                                        ) : (
                                            <MoonIcon className={className} />
                                        )
                                    }
                                />}>切换主题</DropdownItem>
                        <DropdownItem aria-label={'logout-label'} key="logout" color="danger"
                            startContent={<BiLogOutCircle size={18} />}
                            onPress={() => {
                                setExit(!isExit)
                            }}>退出登录</DropdownItem>

                    </DropdownMenu>
                </Dropdown>
            </NavbarContent>
            {/*个人信息*/}
            <Modal backdrop={"blur"} isOpen={isOpen} onOpenChange={onOpenChange}
                placement={"auto"}
                size={"4xl"}
                scrollBehavior={"inside"}>
                <ModalContent>
                    {
                        onClose => (
                            <>
                                <ModalHeader
                                    className={"flex flex-col gap-1 dark:text-white light:text-black text-center"}>个人信息中心</ModalHeader>
                                <ModalBody className="py-2 px-6">
                                    {/* 使用两列布局 */}
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                        {/* 左侧：头像和基本信息 */}
                                        <div className="flex flex-col items-center md:border-r dark:border-gray-700 pr-4">
                                            {/* 头像 */}
                                            <div className="mb-3">
                                                <Avatar
                                                    showFallback
                                                    src={avatar}
                                                    isBordered={true}
                                                    onClick={handleChoosePhoto}
                                                    size="lg"
                                                    className={`cursor-pointer hover:opacity-80 transition-opacity ${isUploading ? 'opacity-50' : ''}`}
                                                    fallback={
                                                        isUploading ?
                                                            <div className="flex items-center justify-center">
                                                                <svg className="animate-spin h-6 w-6 text-default-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                                                </svg>
                                                            </div> :
                                                            <AiFillCamera className="animate-pulse w-6 h-6 text-default-500"
                                                                fill="currentColor" size={20} />
                                                    }
                                                />
                                                <div className="mt-1 text-xs text-center text-gray-500">
                                                    {isUploading ? "上传中..." : "点击更换头像"}
                                                </div>
                                            </div>

                                            {/* 用户名 - 只读 */}
                                            <div className="w-full mb-2">
                                                <Input
                                                    isReadOnly
                                                    id={'username'}
                                                    type="text"
                                                    label="用户名"
                                                    labelPlacement="outside"
                                                    size="sm"
                                                    classNames={{
                                                        label: "text-xs font-normal text-default-500",
                                                        inputWrapper: "border-1"
                                                    }}
                                                    variant={"bordered"}
                                                    placeholder={decodeFromBase64(cookie.load(UserName)).toString()}
                                                    startContent={
                                                        <FiUser className="text-small text-default-400 pointer-events-none flex-shrink-0" />
                                                    }
                                                />
                                            </div>

                                            {/* 昵称 - 可编辑 */}
                                            <div className="w-full mb-2">
                                                <Input
                                                    id={"nickname"}
                                                    type={"text"}
                                                    label={"昵称"}
                                                    value={nickname}
                                                    size="sm"
                                                    classNames={{
                                                        label: "text-xs font-normal text-default-500",
                                                        inputWrapper: "border-1"
                                                    }}
                                                    variant={"bordered"}
                                                    placeholder={"请输入您的昵称"}
                                                    labelPlacement={"outside"}
                                                    onValueChange={(v) => setNickname(v)}
                                                    startContent={
                                                        <CiFries className="text-small text-default-400 pointer-events-none flex-shrink-0" />
                                                    }
                                                />
                                            </div>
                                        </div>

                                        {/* 中间：联系信息 */}
                                        <div className="flex flex-col md:col-span-1">
                                            <h3 className="text-xs font-medium mb-2">联系信息</h3>

                                            {/* 邮箱 */}
                                            <div className="w-full mb-3">
                                                {isEditingEmail ? (
                                                    <div className="space-y-2">
                                                        <Input
                                                            id={'new-email'}
                                                            type="email"
                                                            label="新邮箱"
                                                            size="sm"
                                                            classNames={{
                                                                label: "text-xs font-normal text-default-500",
                                                                inputWrapper: "border-1"
                                                            }}
                                                            variant={"bordered"}
                                                            value={newEmail}
                                                            onChange={e => setNewEmail(e.target.value)}
                                                            placeholder="请输入新邮箱"
                                                            labelPlacement="outside"
                                                            startContent={
                                                                <MailIcon className="text-small text-default-400 pointer-events-none flex-shrink-0" />
                                                            }
                                                        />
                                                        <div className="flex justify-end gap-2">
                                                            <Button size="sm" color="default" variant="light" onClick={() => {
                                                                setIsEditingEmail(false);
                                                                setNewEmail('');
                                                            }}>
                                                                取消
                                                            </Button>
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <div className="flex gap-2">
                                                        <Input
                                                            isReadOnly
                                                            id={'email'}
                                                            type="email"
                                                            label="邮箱"
                                                            size="sm"
                                                            classNames={{
                                                                label: "text-xs font-normal text-default-500",
                                                                inputWrapper: "border-1"
                                                            }}
                                                            variant={"bordered"}
                                                            placeholder={email}
                                                            className="flex-1"
                                                            labelPlacement="outside"
                                                            startContent={
                                                                <MailIcon className="text-small text-default-400 pointer-events-none flex-shrink-0" />
                                                            }
                                                        />
                                                        <Button className="self-end" size="sm" color="primary" variant="flat" onClick={() => {
                                                            setIsEditingEmail(true);
                                                            setNewEmail(email);
                                                        }}>
                                                            修改
                                                        </Button>
                                                    </div>
                                                )}
                                            </div>

                                            {/* 手机号 */}
                                            <div className="w-full mb-3">
                                                <Input
                                                    isReadOnly
                                                    id={'mobile'}
                                                    type="tel"
                                                    label="手机号"
                                                    size="sm"
                                                    classNames={{
                                                        label: "text-xs font-normal text-default-500",
                                                        inputWrapper: "border-1"
                                                    }}
                                                    variant={"bordered"}
                                                    placeholder={mobile || '未绑定'}
                                                    labelPlacement="outside"
                                                    startContent={
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-default-400 pointer-events-none flex-shrink-0">
                                                            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                                                        </svg>
                                                    }
                                                />
                                            </div>

                                            {/* 注册时间 */}
                                            <div className="w-full">
                                                <Input
                                                    isReadOnly
                                                    id={'regTime'}
                                                    type="text"
                                                    label="注册时间"
                                                    size="sm"
                                                    classNames={{
                                                        label: "text-xs font-normal text-default-500",
                                                        inputWrapper: "border-1"
                                                    }}
                                                    variant={"bordered"}
                                                    placeholder={createTime}
                                                    labelPlacement="outside"
                                                    startContent={
                                                        <MdMoreTime className="text-small text-default-400 pointer-events-none flex-shrink-0" />
                                                    }
                                                />
                                            </div>
                                        </div>

                                        {/* 右侧：安全设置 */}
                                        <div className="flex flex-col md:col-span-1 md:border-l dark:border-gray-700 pl-4">
                                            <h3 className="text-xs font-medium mb-2">安全设置</h3>

                                            {!isChangingPassword ? (
                                                <Button
                                                    size="sm"
                                                    color="primary"
                                                    variant="bordered"
                                                    startContent={
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                                            <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                                                            <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                                                        </svg>
                                                    }
                                                    onClick={() => setIsChangingPassword(true)}
                                                >
                                                    修改密码
                                                </Button>
                                            ) : (
                                                <div className="space-y-2">
                                                    <Input
                                                        type="password"
                                                        label="原密码"
                                                        placeholder="请输入原密码"
                                                        size="sm"
                                                        classNames={{
                                                            label: "text-xs font-normal text-default-500",
                                                            inputWrapper: "border-1"
                                                        }}
                                                        variant="bordered"
                                                        value={oldPassword}
                                                        onChange={e => setOldPassword(e.target.value)}
                                                    />
                                                    <Input
                                                        type="password"
                                                        label="新密码"
                                                        placeholder="请输入新密码"
                                                        size="sm"
                                                        classNames={{
                                                            label: "text-xs font-normal text-default-500",
                                                            inputWrapper: "border-1"
                                                        }}
                                                        variant="bordered"
                                                        value={newPassword}
                                                        onChange={e => setNewPassword(e.target.value)}
                                                    />
                                                    <Input
                                                        type="password"
                                                        label="确认密码"
                                                        placeholder="请再次输入新密码"
                                                        size="sm"
                                                        classNames={{
                                                            label: "text-xs font-normal text-default-500",
                                                            inputWrapper: "border-1"
                                                        }}
                                                        variant="bordered"
                                                        value={confirmPassword}
                                                        onChange={e => setConfirmPassword(e.target.value)}
                                                    />
                                                    <div className="flex justify-end gap-2">
                                                        <Button size="sm" color="default" variant="light" onClick={() => {
                                                            setIsChangingPassword(false);
                                                            setOldPassword('');
                                                            setNewPassword('');
                                                            setConfirmPassword('');
                                                        }}>
                                                            取消
                                                        </Button>
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </ModalBody>
                                <ModalFooter className="pt-2">
                                    <Button variant={"flat"} color="default" onClick={(v) => {
                                        modifyUserInfo()
                                    }}>
                                        保存修改
                                    </Button>
                                    <Button variant={"flat"} color="primary" onClick={onClose}>
                                        关闭
                                    </Button>
                                </ModalFooter>
                            </>
                        )
                    }
                </ModalContent>
            </Modal>
            {/*个人设置中心*/}
            <SettingPage isOpenSet={isOpenSet} onOpenSetChange={onOpenSetChange} />

            {/* 搜索模态框 */}
            <SearchModal
                isOpen={isSearchModalOpen}
                onOpenChange={setIsSearchModalOpen}
                initialKeyword={inputValue}
            />
        </>
    )
}
